package com.fun.demo.fun;

import java.io.*;
import java.time.LocalDateTime;

public class CloneUtil<T> {

    public static void main(String[] args) {

//        CaTest c1Child = new CaTest();
//        c1Child.setId(1008);
//        c1Child.setName("邦德的孩子");
//
//        CaTest c1 = new CaTest();
//        c1.setId(1007);
//        c1.setName("邦德");
//        c1.setChild(c1Child);
//
//
//        LocalDateTime t1 = LocalDateTime.now();
//        CaTest newc = new CloneUtil<CaTest>().clone(c1);
//        LocalDateTime t2 = LocalDateTime.now();
//
//
//        System.out.println(newc.getId() + "-" + newc.getName() + ":" + newc.getDate());

    }

    public   T  clone(T t){
        ByteArrayOutputStream bo = null;
        ByteArrayInputStream bi = null;
        ObjectOutputStream oo = null;
        ObjectInputStream oi = null;
        T newt = null;
        try {
            bo = new ByteArrayOutputStream();
            oo = new ObjectOutputStream(bo);
            oo.writeObject(t);

            bi = new ByteArrayInputStream(bo.toByteArray());
            oi = new ObjectInputStream(bi);
            newt =  (T)oi.readObject();

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }finally {
            if(oi != null){
                try {
                    oi.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(oo != null){
                try {
                    oo.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bo != null){
                try {
                    bo.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bi != null){
                try {
                    bi.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return newt;
    }
}
